package com.demo.base.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 资源转码工具类
 * @date 2023/4/2 12:34 AM
 */
@Slf4j
public class SourceConvertUtil {

    /**
     * 视频转音频
     *
     * @param multiFile
     * @return
     */
    public static File videoConvertAudio(MultipartFile multiFile) {

        File videoFile = multipartFileToFile(multiFile);
        if (videoFile == null) {
            log.error("MultipartFile 转 File 失败，文件为空");

            return null;
        }

        try {

            File target =
                    new File("/tmp/" + UUID.randomUUID().toString().replace("-", "") + ".mp3");

            // Audio Attributes
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("libmp3lame");

            // Encoding attributes
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setOutputFormat("mp3");
            attrs.setAudioAttributes(audio);

            // Encode
            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(videoFile), target, attrs);

            return target;

        } catch (Exception ex) {
            log.error("视频转音频失败，异常：{}", ex.getMessage());
        } finally {
            // 删除文件
            if (videoFile.exists()) {
                if (!videoFile.delete()) {
                    log.error("删除文件File失败");
                } else {
                    log.info("文件：{} ，已删除", videoFile.getAbsolutePath());
                }
            }
        }

        return null;
    }

    /**
     * 视频转视频
     *
     * <p>mpeg4视频转为MP4
     *
     * @return
     */
    public static File videoConvertVideo(File mpeg4File) {

        try {
            File target =
                    new File("/tmp/" + UUID.randomUUID().toString().replace("-", "") + ".mp4");

            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("aac");

            VideoAttributes video = new VideoAttributes();
            video.setCodec("libx264");

            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setOutputFormat("mp4");
            attrs.setAudioAttributes(audio);
            attrs.setVideoAttributes(video);

            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(mpeg4File), target, attrs);

            return target;

        } catch (Exception ex) {
            log.error("视频转视频失败，异常：{}", ex.getMessage());
        } finally {
            // 删除文件
            if (mpeg4File.exists()) {
                if (!mpeg4File.delete()) {
                    log.error("删除文件File失败");
                } else {
                    log.info("文件：{} ，已删除", mpeg4File.getAbsolutePath());
                }
            }
        }

        return null;
    }

    /**
     * MultipartFile 转 File
     *
     * @param multiFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multiFile) {

        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            return null;
        }

        // 生成新文件名
        String newFileName = UUID.randomUUID().toString().replace("-", "");

        try {
            File file = File.createTempFile(newFileName, suffix, new File("/tmp"));
            multiFile.transferTo(file);

            return file;
        } catch (Exception e) {
            log.error("MultipartFile 转 File 失败，异常：{}", e.getMessage());
        }

        return null;
    }

    /**
     * 视频url转File
     *
     * @param videoUrl
     * @return
     */
    public static File videoUrlToVideoFile(String videoUrl) {

        File file = new File("/tmp/" + UUID.randomUUID().toString().replace("-", "") + ".mp4");

        try {

            URL url = new URL(videoUrl);
            FileUtils.copyURLToFile(url, file);

            return file;

        } catch (IOException e) {
            log.error("视频下载失败，异常：{}", e.getMessage());
        }

        return null;
    }
}
